package basic;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;


public class SumDemo {

	/**
	 * 统计分数
	 * @param args
	 */
	public static void main(String[] args) throws Exception{
		if (args.length!=2) {
			System.err.println("user infos err: <inpath>,<outpath>");
			System.exit(-1);
		}
		@SuppressWarnings("deprecation")
		Job job = new Job(new Configuration(), "student");
		job.setJarByClass(SumDemo.class);
		//设置输入输出路径:?为什么要删除那个了？？
		FileInputFormat.addInputPath(job, new Path(args[0]));//输入路径
		FileOutputFormat.setOutputPath(job,new Path(args[1]));//输出路径
		
		//设置运行map（），reduce（）的类。
		job.setMapperClass(SumMap.class);
		job.setReducerClass(SumReduce.class);
		//设置map与reduce输出的key，value类型
		//如果map输出的key，value的类型与reduce的输出的key，value相同，则可以省略对map的设置。
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		//提交job
		job.waitForCompletion(true);
		
		
	}
	
	
	public static class SumMap extends Mapper<LongWritable, Text,Text, IntWritable>{
		Text name=new Text();
		IntWritable score=new IntWritable();
		protected void map(LongWritable key, Text value, org.apache.hadoop.mapreduce.Mapper<LongWritable,Text,Text,IntWritable>.Context context) throws java.io.IOException ,InterruptedException {
			String[] lines = value.toString().split(",");
				name.set(lines[0]);
				score.set(Integer.parseInt(lines[1]));
				//map输出的中间结果，<zhangsan,12>
				context.write(name,score);
		};
	}
	/*
	 * map的中间结果需要经过shuffler处理，将相同的key的value放在同一个集合中。
	 * 处理后的结果交给reduce处理。《张三，12，123，1.31》
	 * */
	
	
	public static class SumReduce extends Reducer<Text,IntWritable, Text, IntWritable>{
		protected void reduce(Text k2, java.lang.Iterable<IntWritable> values, org.apache.hadoop.mapreduce.Reducer<Text,IntWritable,Text,IntWritable>.Context context) throws java.io.IOException ,InterruptedException {
			int sum=0;
			for (IntWritable score : values) {
				sum+=score.get();//将hadoop的整型转换成java中的整型，然后进行相加
			}
			context.write(k2, new IntWritable(sum));
		};
	}

}
